package middleware

import (
	"gitee.com/sansaniot/ssiot-core/config"
	jwt "gitee.com/sansaniot/ssiot-core/httpmvc/jwtauth"
	"ssadmin/common/middleware/handler"
	"time"
)

// AuthInit jwt验证new
func AuthInit() (*jwt.GinJWTMiddleware, error) {
	timeout := 1 * time.Hour

	if config.JwtConfig.Timeout != 0 {
		timeout = time.Duration(config.JwtConfig.Timeout) * time.Second
	}

	return jwt.New(&jwt.GinJWTMiddleware{
		Realm:   "sansan",
		Key:     []byte(config.JwtConfig.Secret),
		Timeout: timeout,
		// 刷新token的时候，会根据 token签发时间 + 最大刷新时间 < 当前时间，来判断是否token是否可以刷新
		// 0则无法刷新
		MaxRefresh:      timeout,
		PayloadFunc:     handler.PayloadFunc,     // login认证后生成token payload
		IdentityHandler: handler.IdentityHandler, // 验证token时，从上下文中解析token，得到用户名
		Authenticator:   handler.Authenticator,   // login时认证，查库获取用户信息，设置缓存
		Authorizator:    handler.Authorizator,    // IdentityHandler 解析后，设置上下文
		LoginResponse:   handler.LoginResponse,   // login时返回
		Unauthorized:    handler.Unauthorized,
		RefreshResponse: handler.Refresh,
		TokenLookup:     "header: Authentication, header: token, cookie: token",
		TokenHeadName:   "",
		SendCookie:      false,
		TimeFunc:        time.Now,
	})

}
